<template>
  <el-dialog
    :close-on-click-modal="false"
    :append-to-body="true"
    title="请登录"
    :visible.sync="dialogVisible"
    width="30%"
  >
    <el-form
      class="pl-10 pr-12"
      :model="form"
      :rules="rules"
      ref="form"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      form: {
        username: "admin",
        password: "123123",
      },
      rules: {
        username: [{ required: true, message: "请输入用户名", triger: "blue" }],
        password: [{ required: true, message: "请输入密码", triger: "blue" }],
      },
    };
  },
  methods: {
    open() {
      this.dialogVisible = true;
    },
    close() {
      this.dialogVisible = false;
    },
    onSubmit() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        this.$axios.post("login", this.form).then((res) => {
          const { code, message, data } = res.data;
          if (code === 200) {
            this.$store.commit("loggedIn", data);
            this.$message.success("登录成功");
            this.resetForm();
            this.close();
          } else {
            this.$message.error(message);
          }
        });
      });
    },
    resetForm() {
      this.$refs["form"].resetFields();
    },
  },
};
</script>